<template>
  <div class="app-container order-class">
    <el-row style="margin-bottom:10px">
      <el-col :span="3">
        <el-input v-model="search.keyword" placeholder="Keyword" style="width:95%" />
      </el-col>
      <el-col :span="3">
        <el-select v-model="search.order_state" clearable placeholder="Please Choose Status" style="width:95%" no-data-text="Can't find record">
          <el-option
            v-for="item in statuslist"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-col>
      <el-button type="primary" icon="el-icon-search" @click="gettableinto" />
      <!-- <el-button v-show="createShow" type="primary" @click="handleAddRole">Add</el-button> -->
    </el-row>
    <el-table
      :data="rolesList"
      style="width: 100%;margin-top:30px;"
      :cell-style="cellChangeColor"
      :empty-text="empty_text"
      border
    >
      <el-table-column align="center" prop="id" label="ID" width="50">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>

      <el-table-column align="left" label="Order No." prop="order_no" width="180">
        <template slot-scope="scope">
          <el-link @click="userOrderDetail(scope)">{{ scope.row.order_no }}</el-link>
        </template>
      </el-table-column>

      <el-table-column align="header-center" label="Services" min-width="150">
        <template slot-scope="scope">{{ scope.row.goods.map(v=> v.goods_name).join(',') }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Customer Name" width="130">
        <template slot-scope="scope">{{ scope.row.receiver_name }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Condominium" min-width="140">
        <template slot-scope="scope">{{ (scope.row.receiver_info.condominium_name? scope.row.receiver_info.condominium_name : '') }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Address" min-width="140">
        <template slot-scope="scope">{{ ' Blk ' + scope.row.receiver_info.block + ',#' + scope.row.receiver_info.floor + '-' + scope.row.receiver_info.unit }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Time slot (Date & Time)" width="250">
        <template slot-scope="scope">{{ scope.row.timeslot }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Order Amount" width="120">
        <template slot-scope="scope">{{ scope.row.order_amount }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Order Status" width="110">
        <template slot-scope="scope">{{ scope.row.order_state_desc }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Order Time" width="160">
        <template slot-scope="scope">{{ scope.row.create_time }}</template>
      </el-table-column>
      <el-table-column align="center" label="Action" width="120">
        <template slot-scope="scope">
          <el-row>
            <el-col :span="6">
              <!-- <el-link v-show="editShow" class="el-icon-edit icon-class" @click="handleAddAddress(scope)" /> -->
              <el-link v-show="editShow" class="el-icon-location-outline icon-class" @click="handleAddAddress(scope)" />
            </el-col>
            <el-col :span="6">
              <el-link class="el-icon-document icon-class" @click="handleAddRole(scope)" />
            </el-col>
            <el-col :span="6">
              <!-- <el-link class="el-icon-edit-outline icon-class" @click="handleRefund(scope)" /> -->
              <el-link class="el-icon-customize icon-class" @click="handleRefund(scope)" />
            </el-col>
            <el-col :span="6">
              <el-link v-show="editShow" class="el-icon-delete icon-class" @click="handleDelete(scope)" />
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? 'Edit Work Order' : 'New Work Order'"
    >
      <div style="margin:0 30px">
        <el-form ref="connectForm" :model="orderinfo" :rules="rules" label-width="150px" label-position="left">
          <el-form-item label="Title" prop="title">
            <el-input v-model="orderinfo.title" placeholder="Title" value="Handyfix" />
          </el-form-item>
          <el-form-item label="Room & Others" prop="desc">
            <el-input v-model="orderinfo.desc" placeholder="Room & Others" />
          </el-form-item>
          <el-form-item label="Priority" prop="priority">
            <el-select v-model="orderinfo.priority" placeholder="Please Choose" no-data-text="Can't find record">
              <el-option
                v-for="item in prioritylist"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="Client" prop="hotel_id">
            <el-select v-model="orderinfo.hotel_id" placeholder="Please Choose" no-data-text="Can't find record" @change="gethotelcontectinfo">
              <el-option
                v-for="item in hotellist"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="Client Contact" prop="hotecontectlids" >
            <el-select v-model="hotecontectlids" style="width:100%" placeholder="Please Choose" no-data-text="Can't find record">
              <el-option
                v-for="item in hotecontectllist"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="Work Instructions" prop="wiids">
            <el-select v-model="wiids" style="width:100%" multiple placeholder="Please Choose" no-data-text="Can't find record">
              <el-option
                v-for="item in wilist"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="Staffs" prop="staffsids">
            <el-select v-model="staffsids" style="width:100%" multiple placeholder="Please Choose" no-data-text="Can't find record">
              <el-option
                v-for="item in staffslist"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="Due date">
            <el-date-picker v-model="orderinfo.due_date" type="datetime" placeholder="End Date" />
          </el-form-item>
          <el-form-item v-if="notesText.length > 0" label="Note">
            <el-input v-model="notesText" type="textarea" :autosize="{ minRows: 2 }" placeholder="Note" disabled />
          </el-form-item>

          <!-- <el-form-item v-for="(note, index) in orderinfo.notes" :key="index" label="Note">
            <el-input v-model="orderinfo.notes[index]" placeholder="Note" />
          </el-form-item> -->
          <el-form-item label="Note">
            <el-input v-model="orderinfo.goods_list" placeholder="Note" />
          </el-form-item>

        </el-form>
        <el-button size="mini" icon="el-icon-circle-plus" @click="add" />
        <div style="text-align:right;">
          <el-button type="danger" @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="confirm">Confirm</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogVisible_add"
      :title="'Change Address'"
    >
      <div style="margin:0 30px">
        <el-form ref="add_connectForm" :model="addressinfo" :rules="add_rules" label-width="130px" label-position="left">
          <el-form-item label="Receiver Name" prop="receiver_name">
            <el-input v-model="addressinfo.receiver_name" placeholder="Receiver Name" />
          </el-form-item>
          <el-form-item label="Receiver Mobile" prop="receiver_mobile">
            <el-input v-model="addressinfo.receiver_mobile" placeholder="Receiver Mobile" />
          </el-form-item>
          <el-form-item label="Condominium" prop="condominium_id">
            <el-select v-model="addressinfo.condominium_id" clearable placeholder="Please Choose Status" style="width:100%" no-data-text="Can't find record">
              <el-option
                v-for="item in condominiumlist"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="Block" prop="block">
            <el-input v-model="addressinfo.block" placeholder="Block" />
          </el-form-item>
          <el-form-item label="Floor" prop="floor">
            <el-input v-model="addressinfo.floor" placeholder="Floor" />
          </el-form-item>
          <el-form-item label="Unit" prop="unit">
            <el-input v-model="addressinfo.unit" placeholder="Unit" />
          </el-form-item>
        </el-form>
        <div style="text-align:right;">
          <el-button type="danger" @click="dialogVisible_add = false">Cancel</el-button>
          <el-button type="primary" @click="confirmAdd">Confirm</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogVisible_per"
      title="Download"
      width="500px"
    >
      <div>
        <el-row style="margin-bottom:20px;margin-top: -10px;padding-left: 20px">
          <el-col v-for="item in total_row_total" :key="item" :span="6" style="margin-bottom:10px">
            <el-link type="primary" @click="downloadWorkOrder(item)">Page {{ item }}</el-link>
          </el-col>
        </el-row>
      </div>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible_per = false">Cancel</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogVisible_refund"
      title="Refund"
      width="800px"
    >
      <div style="margin:0 30px">
        <el-form ref="refund_connectForm" :model="refundInfo" :rules="refund_rules" label-width="80px" label-position="left">
          <el-form-item label="Reason" prop="reason">
            <el-input v-model="refundInfo.reason" type="textarea" :autosize="{ minRows: 2 }" placeholder="Reason" />
          </el-form-item>
        </el-form>
        <div style="text-align:right;">
          <el-button type="danger" @click="dialogVisible_refund = false">Cancel</el-button>
          <el-button type="primary" @click="confirmRefund">Confirm</el-button>
        </div>
      </div>
    </el-dialog>

    <el-pagination
      style="margin-top:10px;float:right"
      background
      layout="slot,prev,pager,next"
      :total="totalpage"
      :current-page="search.page"
      :page-size="search.per_page"
      @current-change="handleIndexChange"
    >
      <span class="el-pagination__total">Total {{ totalpage }}</span>
    </el-pagination>
  </div>
</template>

<script>
import { baseAPI } from '@/utils/request'
// import MyTest from './noets.vue'
import {
  getorderinfo,
  getdictionary,
  deleteorder,
  editAddress,
  getdetails,
  refundOrder
} from '@/api/handyFix/index'

import {
  saveorder
} from '@/api/order/index'
import { parseTime } from '@/utils'
import { getToken } from '@/utils/auth' // get token from cookie

const defaultOrderInfo = {
  id: '',
  title: '',
  desc: '',
  priority: '',
  hotel_id: '',
  hotel_contact_ids: [],
  wi_ids: [],
  notes: [],
  staffs: [],
  due_date: '',
  order_id: '',
  goods_list: ''
}

const defaultAddressInfo = {
  id: '',
  condominium_id: '',
  block: '',
  floor: '',
  unit: '',
  receiver_name: '',
  receiver_mobile: ''
}

const defaultRefundInfo = {
  order_id: '',
  reason: ''
}
export default {
  components: {
    // MyTest
  },
  data() {
    return {
      total_row_num: 50,
      total_row_total: undefined,
      createShow: false,
      editShow: false,
      emailVisible: false,
      dialogVisible_per: false,
      dialogVisible_refund: false,
      emailModel: {
        emails: ['']
      },
      statuslist: [],
      addressinfo: {
        id: '',
        condominium_id: '',
        block: '',
        floor: '',
        unit: '',
        receiver_name: '',
        receiver_mobile: ''
      },
      refundInfo: {
        order_id: '',
        reason: ''
      },
      orderinfo: {
        id: '',
        title: '',
        desc: '',
        priority: 2,
        hotel_id: '',
        hotel_contact_ids: [],
        wi_ids: [],
        notes: [],
        staffs: [],
        due_date: '',
        order_id: '',
        goods_list: ''
      },
      search: {
        keyword: '',
        page: 1,
        order_state: '',
        per_page: 10
      },
      notesText: '',
      notes: [{
        note: ''
      }],
      empty_text: '',
      prioritylist: [],
      hotellist: [],
      hotecontectllist: [],
      hotecontectlids: '',
      wilist: [],
      wiids: [],
      staffslist: [],
      staffsids: [],
      totalpage: 0,
      routes: [],
      rolesList: [],
      condominiumlist: [],
      dialogVisible: false,
      dialogVisible_add: false,
      dialogType: 'new',
      checkStrictly: false,
      tokenData: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      emailRules: {
        email: [
          { type: 'email', message: 'Please enter the correct email format', trigger: 'blur' }]
      },
      rules: {
        title: [{ required: true, message: 'Please enter a title', trigger: 'blur'
        }],
        desc: [{ required: true, message: 'Please Enter Room & Others', trigger: 'blur'
        }],
        priority: [{ required: true, message: 'Please Choose Priority', trigger: 'change'
        }],
        hotel_id: [{ required: true, message: 'Please Choose Hotel', trigger: 'change'
        }]
      },
      add_rules: {
        condominium_id: [{ required: true, message: 'Please Select a Condominium' }],
        block: [{ required: true, message: 'Please enter a block', trigger: 'blur'
        }],
        floor: [{ required: true, message: 'Please enter a floor', trigger: 'blur'
        }],
        unit: [{ required: true, message: 'Please enter a unit', trigger: 'blur'
        }],
        receiver_name: [{ required: true, message: 'Please enter a Receiver Name', trigger: 'blur'
        }],
        receiver_mobile: [{ required: true, message: 'Please enter a Receiver Mobile', trigger: 'blur'
        }]
      },
      refund_rules: {
        reason: [{ required: true, message: 'Please enter a Refund Reason', trigger: 'blur' }]
      }
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  watch: {
    dialogVisible(newValue, oldValue) {
      this.addressinfo = Object.assign({}, defaultAddressInfo)
      if (this.$refs['connectForm']) this.$refs['connectForm'].clearValidate()

      if (!newValue) {
        this.notesText = ''
        this.orderinfo = Object.assign({}, defaultOrderInfo)
      } else {
        this.orderinfo.notes = []
        this.orderinfo.notes.push('')
      }
    },
    dialogVisible_add(newValue, oldValue) {
      if (this.$refs['add_connectForm']) this.$refs['add_connectForm'].clearValidate()

      if (!newValue) {
        this.addressinfo = Object.assign({}, defaultAddressInfo)
      }
    },
    dialogVisible_refund(newValue, oldValue) {
      if (this.$refs['refund_connectForm']) this.$refs['refund_connectForm'].clearValidate()

      if (!newValue) {
        this.refundInfo = Object.assign({}, defaultRefundInfo)
      }
    },
    emailVisible(newValue, oldValue) {
      if (this.$refs['emailForm']) this.$refs['emailForm'].clearValidate()
      if (!newValue) {
        this.emailModel.emails = ['']
      }
    }
  },
  created() {
    // Mock: get all routes and roles list from server
    this.getRoutes()
    this.getRoles()
    this.conRouter()
    this.conToken()
    if (this.$route.query && this.$route.query.order_no) {
      // 业务逻辑
      this.search.keyword = this.$route.query.order_no
    }
  },
  methods: {
    addEmail() {
      this.emailModel.emails.push('')
    },
    delEmail(val) {
      this.emailModel.emails.splice(val, 1)
    },
    add() {
      this.orderinfo.notes.push('')
      // this.notes.push({
      //   note: ''
      // })
    },
    cellChangeColor({ row, column, rowIndex, columnIndex }) {
      if (row.status === 2 && columnIndex === 6) { return { backgroundColor: '#9267be', color: 'white' } }
      if (row.status === 3 && columnIndex === 6) { return { backgroundColor: '#6ed3d0' } }
      if (row.overdue && columnIndex === 5) { return { backgroundColor: '#f74969', color: 'white' } }
      return ''
    },
    status_change(scope) {
      if (scope.row.status === 1) {
        return 'table-info-row1'
      } else if (scope.row.status === 2) {
        return 'table-info-row2'
      } else if (scope.row.status === 3) {
        return 'table-info-row3'
      }
    },
    handleIndexChange(index) {
      this.search.page = index
      this.getRoles()
    },
    async getRoutes() {
      const res = await baseAPI.get('user/role/routes')
      this.serviceRoutes = res
      this.routes = res
    },
    async conRouter() {
      const { roles, role_infos } = await this.$store.dispatch('user/getInfo')
      if (roles.some(p => p === '1')) {
        this.createShow = true
        this.editShow = true
      } else {
        const res = role_infos[0].routes
        this.createShow = res.some(p => p === '/order/add')
        this.editShow = res.some(p => p === '/order/edit')
      }
    },
    async conToken() {
      this.tokenData = getToken()
    },
    gettableinto() {
      this.keyword = this.keywords
      this.getRoles()
    },
    async getRoles() {
      this.empty_text = 'Loading ......'
      await getorderinfo(this.search).then(response => {
        // console.log(response)
        this.rolesList = response.data
        this.totalpage = response.total
        this.per_page = response.per_page
        this.current_page = response.current_page
        this.empty_text = 'Can\'t find record in table'
      }).catch(() => {
        this.rolesList = []
        this.empty_text = 'Can\'t find record in table'
      })
      await this.gethotelinfo()
    },
    async gecondominiuminfo() {
      this.condominiumlist = await getdictionary({ dict_type: 'condominium' })
    },
    async getpriorityinfo() {
      this.prioritylist = await getdictionary({ dict_type: 'priority' })
      this.orderinfo.priority = 2
    },
    async gethotelinfo(new_push = false) {
      this.hotellist = await getdictionary({ dict_type: 'hotel' })
      if (new_push) {
        console.log(new_push)
        let push_add = true
        const handyfix_new_name = 'HandyFix-' + new_push.name
        this.hotellist.forEach(raw => {
          if (raw.name === handyfix_new_name) {
            push_add = false
            this.orderinfo.hotel_id = raw.value
            this.hotellist = [{
              name: raw.name,
              value: raw.value
            }]
            return
          }
        })
        if (push_add) {
          this.hotellist.push(new_push)
          this.orderinfo.hotel_id = handyfix_new_name
          this.hotellist = [{
            name: handyfix_new_name,
            value: handyfix_new_name
          }]
        }
      }

      this.statuslist = await getdictionary({ dict_type: 'order_search_status' })
      if (this.search.order_state === '') this.search.order_state = 20 // 默认选中 20Paid已付费
    },
    async gethotelcontectinfo(val) {
      this.hotecontectllist = await getdictionary({ dict_type: 'hotel_contact', hotel_id: val })
      this.hotecontectlids = ''
      this.wiids = []
      this.getwiinfo(val)
    },
    async getwiinfo(val) {
      this.wilist = await getdictionary({ dict_type: 'wi', hotel_id: val })
      this.wilist.unshift({ name: 'Handyfix(default)', value: 1 })
    },
    async getstaffsinfo(val) {
      this.staffslist = await getdictionary({ dict_type: 'staff' })
    },
    handleAddAddress(scope) {
      this.gecondominiuminfo()
      this.addressinfo.id = scope.row.id
      this.addressinfo.condominium_id = scope.row.receiver_info.condominium_id
      this.addressinfo.block = scope.row.receiver_info.block
      this.addressinfo.floor = scope.row.receiver_info.floor
      this.addressinfo.unit = scope.row.receiver_info.unit
      this.addressinfo.receiver_name = scope.row.receiver_name
      this.addressinfo.receiver_mobile = scope.row.receiver_mobile
      this.dialogVisible_add = true
    },
    handleRefund(scope) {
      this.dialogVisible_refund = true
      this.refundInfo.order_id = scope.row.id
    },
    userOrderDetail(scope) {
      // console.log('scope.row.id')
      // console.log(scope.row.id)
      this.$router.push({
        path: '/handyFix/orderdetails',
        query: { id: scope.row.id }
      })
    },
    handleAddRole(scope) {
      this.notes.splice(this.notes)
      this.notes.push({ note: '' })
      this.hotecontectlids = ''
      this.wiids = []
      this.staffsids = []
      this.orderinfo.order_id = scope.row.id

      this.orderinfo.title = 'Handyfix'

      this.orderinfo.desc = scope.row.receiver_info.condominium_name + ' Blk ' + scope.row.receiver_info.block + ',#' + scope.row.receiver_info.floor + '-' + scope.row.receiver_info.unit

      this.orderinfo.due_date = scope.row.timeslot_text
      this.orderinfo.goods_list = scope.row.goods_list

      // this.orderinfo.notes.push('')
      this.getpriorityinfo()

      this.wilist = [{ name: 'Handyfix(default)', value: 1 }]

      this.hotellist = []
      this.gethotelinfo({
        name: scope.row.receiver_name,
        value: scope.row.receiver_name
      })

      this.getstaffsinfo()
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    async handleEdit(scope) {
      this.notes.splice(this.notes)
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      this.getpriorityinfo()
      this.gethotelinfo()
      this.getstaffsinfo()
      const res = await getdetails({ id: scope.row.id })
      await this.gethotelcontectinfo(res.hotel_id)
      this.orderinfo.id = res.id
      this.orderinfo.title = res.title
      this.orderinfo.desc = res.desc
      this.orderinfo.priority = res.priority
      this.orderinfo.hotel_id = res.hotel_id
      this.orderinfo.due_date = new Date(res.due_date.replace('-', '').replace('PM', '').replace('AM', ''))
      this.hotecontectlids = res.hotel_contact && res.hotel_contact.length > 0 ? res.hotel_contact[0].id : ''
      // this.hotecontectlids = res.hotel_contact.map(function(v) { return v.id })
      this.wiids = res.wi.map(function(v) { return v.wi_id })
      this.staffsids = res.staffs.map(function(v) { return v.id })
      for (var i = 0; i < res.notes.length; i++) {
        this.notes.push({ note: res.notes[i].note })
      }
      this.notesText = res.notes.map(element => element.user_name + ': ' + element.note).join('\r\n')
    },
    handleDelete({ $index, row }) {
      this.$confirm('Confirm to remove the Order?', 'Warning', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      })
        .then(async() => {
          await deleteorder({ id: row.id })
          // baseAPI.get('user/witemplate/delete?id=' + row.id + '')
          this.rolesList.splice($index, 1)
          this.getRoles()
          this.$message({
            type: 'success',
            message: 'Delete succed!'
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    openorderdetailsComp(scope) {
      this.$router.push({
        path: '/order/orderdetails',
        query: { id: scope.row.id }
      })
    },
    async confirmAdd() {
      this.$refs.add_connectForm.validate(async valid => {
        if (valid) {
          await editAddress(this.addressinfo)
          this.dialogVisible_add = false
          await this.getRoles()
        }
      })
    },
    async confirm() {
      this.$refs.connectForm.validate(async valid => {
        if (valid) {
          if (this.orderinfo.due_date) {
            this.orderinfo.due_date = parseTime(this.orderinfo.due_date, '{y}-{m}-{d}  {h}:{i}:{s}')
          }
          this.orderinfo.hotel_contact_ids = []
          this.orderinfo.hotel_contact_ids.push(this.hotecontectlids)
          this.orderinfo.wi_ids = this.wiids
          this.orderinfo.staffs = this.staffsids
          this.orderinfo.notes = this.orderinfo.notes.filter(note => note && note.trim())
          // this.orderinfo.notes = this.notes
          // this.orderinfo.notes = this.notes.map(function(v) { return v.note })
          // console.log(this.orderinfo)
          await saveorder(this.orderinfo)
          this.$message({
            type: 'success',
            message: 'Work Order Created Successed!'
          })
          this.dialogVisible = false
          await this.getRoles()
        }
      })
    },
    async confirmRefund() {
      this.$refs.refund_connectForm.validate(async valid => {
        if (valid) {
          const data = {
            order_id: this.refundInfo.order_id,
            payment_type: 1,
            refund_reason: this.refundInfo.reason
          }

          await refundOrder(data)
          this.dialogVisible_refund = false
          await this.getRoles()
        }
      })
    },
    async selectPage() {
      if (!this.total_row_num || this.total_row_num <= 0) {
        this.$message({
          type: 'warning',
          message: 'Please enter the quantity per page!'
        })
        return
      } else {
        const per_search = Object.assign({}, this.search)
        per_search.request_type = 'download_query'

        await getorderinfo(per_search).then(async response => {
          if (response.total > 0) {
            this.total_row_total = Math.ceil(response.total / this.total_row_num)
            this.dialogVisible_per = true
          } else {
            this.$message({
              type: 'warning',
              message: 'Can\'t find record to download!'
            })
          }
        })
      }
    },
    async downloadWorkOrder(value) {
      this.downloadSearch = Object.assign({}, this.search)
      this.downloadSearch.download = 1
      if (this.downloadSearch.time_start) {
        this.downloadSearch.time_start = parseTime(this.downloadSearch.time_start, '{y}-{m}-{d}')
      }
      if (this.downloadSearch.time_end) {
        this.downloadSearch.time_end = parseTime(this.downloadSearch.time_end, '{y}-{m}-{d}')
      }
      const url = 'user/order/index?keyword=' + this.downloadSearch.keyword + '&page=' + value + '&per_page=' + this.total_row_num + '&hotel_id=' + this.downloadSearch.hotel_id +
      '&time_start=' + this.downloadSearch.time_start + '&time_end=' + this.downloadSearch.time_end + '&request_type=download&token=' + this.tokenData
      console.log(url)
      window.open('http://work.dcloud.yunku.live/api/' + url)
    },
    async sendEmail() {
      this.$refs.emailForm.validate(async valid => {
        if (valid) {
          this.downloadSearch = Object.assign({}, this.search)
          this.downloadSearch.download = 1
          if (this.downloadSearch.time_start) {
            this.downloadSearch.time_start = parseTime(this.downloadSearch.time_start, '{y}-{m}-{d}')
          }
          if (this.downloadSearch.time_end) {
            this.downloadSearch.time_end = parseTime(this.downloadSearch.time_end, '{y}-{m}-{d}')
          }
          const requestEmail = this.emailModel.emails.join(',')
          const url = 'user/order/index?keyword=' + this.downloadSearch.keyword + '&page=' + this.downloadSearch.page + '&hotel_id=' + this.downloadSearch.hotel_id +
          '&time_start=' + this.downloadSearch.time_start + '&time_end=' + this.downloadSearch.time_end + '&request_type=send_email&emails=' + requestEmail
          await baseAPI.get(url)
          this.emailVisible = false
          this.$message({
            type: 'success',
            message: 'Email sent successfully!'
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
  .icon-class {
    font-size: 20px;
  }
  .el-icon-customize {
    background: url('../../assets/image/refund.png') center center no-repeat;
    background-size: 20px auto;
    height: 20px;
    width: 20px;
    vertical-align: middle;
    display: inline-block;
  }
}
</style>

<style>
.table-info-row1 td {
      color: #03be1cef;
 }
.table-info-row2 td {
      color: #0057facb;
 }
.table-info-row3 td {
      color: #fd0000c5;
 }
.order-class .el-table .cell {
  white-space: pre-line !important;
}
</style>
